package com.jshan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jshan.base.entity.SysDept;
import com.jshan.mapper.SysDeptMapper;
import com.jshan.service.SysDeptService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Override
    public List<SysDept> listAll() {
        return this.list(new LambdaQueryWrapper<SysDept>()
                .orderByAsc(SysDept::getOrderNum));
    }

    @Override
    public List<SysDept> listWithTree() {
        // 1. 查询所有部门
        List<SysDept> depts = this.list(new LambdaQueryWrapper<SysDept>()
                .orderByAsc(SysDept::getOrderNum));

        // 2. 组装成树形结构
        return depts.stream()
                .filter(dept -> dept.getParentId() == 0)
                .map(dept -> {
                    dept.setChildren(getChildren(dept, depts));
                    return dept;
                })
                .collect(Collectors.toList());
    }

    @Override
    public IPage<SysDept> getDeptPage(IPage<SysDept> page, String depName) {
        LambdaQueryWrapper<SysDept> w = new LambdaQueryWrapper<SysDept>();
        if (StringUtils.isNotBlank(depName)) {
            w.like(SysDept::getName, depName);
        }
        return this.page(page, w.orderByAsc(SysDept::getOrderNum));
    }

    private List<SysDept> getChildren(SysDept root, List<SysDept> all) {
        return all.stream()
                .filter(dept -> dept.getParentId().equals(root.getId()))
                .map(dept -> {
                    dept.setChildren(getChildren(dept, all));
                    return dept;
                })
                .collect(Collectors.toList());
    }
}
